const express = require(`express`);
let Router = express.Router();

// 获取所有英雄数据
Router.get(`/getHeroList`, (req, res) => {
  let { heroName } = req.query;
  // heroName没有值就查询全部 isdelete = 0 的就是全部没有删除的
  let sql = `SELECT * FROM heros WHERE isdelete = 0 `;
  // 有值就拼接条件
  if (heroName) {
    sql += ` and name = "${heroName}" ;`;
  }
  // 访问数据库获取信息
  res.execSql(sql, (err, result) => {
    // 响应
    if (err) {
      res.send({ msg: err.message });
      return;
    }
    res.send({ code: 200, msg: "请求成功", data: result });
  });
});

// 添加英雄数据
Router.post(`/addHero`, (req, res) => {
  let { name, gender, img } = req.body;
  if (!name) {
    res.send({ code: 201, msg: "参数name不能为空" });
    return;
  }

  let sql = `INSERT INTO heros (name,gender,img,isdelete) VALUES("${name}","${gender}","${img}",0)`;
  res.execSql(sql, (err, result) => {
    if (err) {
      res.send({ code: 500, msg: err.message });
      return;
    }
    res.send({ code: 200, msg: "添加成功" });
  });
});

// 删除单个英雄
Router.get(`/delHeroById/:id`, (req, res) => {
    // 这种传参方式 用req.params来接收 是个对象
  let { id } = req.params;
  if (!id || isNaN(id)) {
    res.send({ code: 500, msg: "服务器处理失败：" });
    return;
  }
  let sql = `update heros set isdelete = 1 where id = "${id}";`;
  res.execSql(sql,(err,result)=>{
      if(err){
          res.send({ code: 500, msg: err.message });
          return;
      }
      res.send({"code":200,"msg":"删除数据成功"});
  })
});

//根据id获取单个英雄
Router.get(`/getHeroById`,(req,res)=>{
    let { id } = req.query;
  if (!id || isNaN(id)) {
    res.send({ code: 500, msg: "服务器处理失败：" });
    return;
  };
  let sql = `select * from heros where id = "${id}" and isdelete = 0 ;`;
  res.execSql(sql,(err,result)=>{
    if(err){
        res.send({ code: 500, msg: err.message });
        return;
    };
    res.send({"code": 200,"msg": "请求成功","data": result[0]});
  })
})

// 更新英雄数据
Router.post(`/updateHero`,(req,res)=>{
    let { id , name , gender , img } = req.body;
    if(!id || isNaN(id) || !name){
        res.send({"code":201,"msg":"id或name不合法，请重试"});
        return;
    }
    let sql = `update heros set name = "${name}" , gender = "${gender}" , img = "${img}" where id = "${id}" and isdelete = 0 ;`;
    res.execSql(sql,(err,result)=>{
        if(err){
            res.send({code:500,msg:err.message});
            return;
        }
        if(result.affectedRows === 0 ){
            res.send({code:500,msg:`数据不存在，修改失败`});
            return;
        };
        res.send({"code":200,"msg":"数据更新成功"});

    })
});



const multer = require(`multer`);
const path = require(`path`);
const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        console.log(req,file);
      cb(null, 'uploads/')
    },
    filename: function (req, file, cb) {
        console.log(req,file);
       /*  file
        {
            fieldname: 'file_data',
            originalname: 'src=http _i1.hdslb.com_bfs_archive_3fae16f8cf649baf6d00a2bfe29cbcaa849ce7ea.jpg&refer=http _i1.hdslb.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg.jpg',
            encoding: '7bit',
            mimetype: 'image/jpeg'
          } */
        //   文件名只要后缀名和时间轴
      cb(null, Date.now()+ path.extname(file.originalname) );
    }
  })
   
const upload = multer({ storage: storage })
// 上传头像
Router.post('/uploadFile', upload.single('file_data'), (req, res)=>{
        console.log(req.file);
        /* {
            fieldname: 'file_data',
            originalname: 'src=http _i1.hdslb.com_bfs_archive_3fae16f8cf649baf6d00a2bfe29cbcaa849ce7ea.jpg&refer=http _i1.hdslb.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg.jpg',
            encoding: '7bit',
            mimetype: 'image/jpeg',
            destination: 'uploads/',
            filename: '1624520974090.jpg',
            path: 'uploads\\1624520974090.jpg',
            size: 111125
          } */
        res.send({ code:200, msg:"上传成功", src:`http://127.0.0.1:3001/${req.file.path}`});
})






// 导出
module.exports = Router;
